<?php

class BuyAction extends Action {
        private $Spay;
	private $msgSender = '116680';
	private $key = '2832690750';
        public function _initialize(){
		vendor('ShengPay.ShengPay');
		$this->Spay = new ShengPay();
		$this->Spay->setKey($this->key);
	}
    public function index() {
       $this->display();
    }
    
    function topay()
    {
        $data = array('order_no'=>uniqid(),'total_fee'=>$_POST['jifen']*1.5,'subject'=>'购买积分','extra_common_param'=>$_POST['jifen']);
        $order = M('order');
		$order->add(array('user_id'=>$_SESSION['m_user']['id'],'order_no'=>$data['order_no'],'order_create_time'=>time(),'order_total_fee'=>$data['total_fee'],'trade_no'=>'','order_status'=>'0'));

        $array=array(
			'Name'=>'B2CPayment',
			'Version'=>'V4.1.1.1.1',
			'Charset'=>'UTF-8',
			'MsgSender'=>$this->msgSender,
			'SendTime'=>date('YmdHis'),
			'OrderTime'=>date('YmdHis'),
			'PayType'=>'',
			'InstCode'=>'',
			'PageUrl'=>'http://'.$_SERVER['HTTP_HOST'].'/mobile.php/Buy/pageUrl',
			'NotifyUrl'=>'http://'.$_SERVER['HTTP_HOST'].'/mobile.php/Buy/notifyUrl',
			'ProductName'=>$data['subject'],
			'BuyerContact'=>'service@addindex.com',
			'BuyerIp'=>'',
			'Ext1'=>$data['extra_common_param'],
			'Ext2'=>'',
			'SignType'=>'MD5',
		);
		$this->Spay->init($array);
		$this->Spay->takeOrder($data['order_no'],$data['total_fee']);
    }
    
    //同步
	public function pageUrl (){
		unset($_GET['_URL_']);
	
		if($this->Spay->returnSign()){
			$this->_doSuccess();
		}
	}
	
	//异步
	public function notifyUrl (){
		if ($this->Spay->returnSign()){
			$this->_doSuccess();	
			echo 'OK';
		}
	}
        
        function _doSuccess(){
           $out_trade_no	= $this->_request('OrderNo');	//获取订单号
		$trade_no		= $this->_request('TransNo');		
		$total_fee		= $this->_request('TransAmount');		//获取总价格
		$Order			= M('Order');
		$row			= $Order -> field('order_status') -> where(array('order_no'=>$out_trade_no)) -> find();
		if ($row['order_status'] != 1){
			$Order	-> where(array('order_no'=>$out_trade_no)) -> save(array('trade_no'=>$trade_no,'order_status'=>1));
		}
		$User				= M('User');
		$User_id			= M('Order')->field('user_id')->where(array('order_no'=>$this->_request('OrderNo')))->find();
		$jifen = floor($this->_request('Ext1'));
		$User				->where('id = '.$User_id['user_id']) -> setInc('jifen',$jifen);
		$_SESSION['m_user']['jifen'] 		+= $jifen;
		$this->success('支付成功','/mobile.php');
       }
}